package com.peanut.baby.mvp.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.igexin.sdk.BuildConfig;
import com.peanut.baby.AppConfig;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.comm.DingyueDialog;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.UStatus;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.ask.AskActivity;
import com.peanut.baby.mvp.bbs.publish.BBSPublishActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.calendar.CalendarActivity;
import com.peanut.baby.mvp.dingyue.DingyueActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.main.circle.CircleFragment;
import com.peanut.baby.mvp.main.expert.ExpertFragment;
import com.peanut.baby.mvp.trend.publish.TrendPublishActivity;
import com.peanut.baby.mvp.search.SearchActivity;
import com.peanut.baby.mvp.subscribe.TagSubscribeActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.Cache;
import com.peanut.baby.util.PrefUtil;
import com.peanut.devlibrary.adapter.FragmentTabAdapter;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.peanut.devlibrary.widget.FloatMenuMgr;
import com.peanut.devlibrary.widget.TabRadioButton;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/5.
 */

public class MainActivity extends BaseMvpActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener, View.OnClickListener,MainActivityContract.View {
    private static final String TAG = MainActivity.class.getSimpleName();
    @BindView(R.id.main_viewpager)
    ViewPager mainViewpager;
    @BindView(R.id.tab_home)
    TabRadioButton tabHome;
    @BindView(R.id.tab_expert)
    TabRadioButton tabExpert;
    @BindView(R.id.tab_circle)
    TabRadioButton tabCircle;
    @BindView(R.id.tab_profile)
    TabRadioButton tabProfile;
    @BindView(R.id.main_tab_radio)
    RadioGroup mainTabRadio;
    @BindView(R.id.tab_functions)
    RelativeLayout tabFunctions;
    private long mTimestamp = 0L;

    private FragmentTabAdapter mAdapter;
    private ArrayList<Fragment> mFragments;

    private HomeFragment homeFg;
    private ExpertFragment expertFg;
    private CircleFragment circleFg;
    private ProfileFragment profileFg;

    private MainActivityPresenter presenter;

    /**
     * @param ctx
     */
    public static void start(Context ctx) {
        Intent intent = new Intent(ctx, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        ctx.startActivity(intent);
    }



    private void registTaskReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConfig.BroadCastConfig.ACTION_TASK_BBS);
        filter.addAction(AppConfig.BroadCastConfig.ACTION_TASK_QA);
        filter.addAction(AppConfig.BroadCastConfig.ACTION_TASK_LIVE);
        filter.addAction(AppConfig.BroadCastConfig.ACTION_TASK_REPLY);
        registerReceiver(taskReceiver, filter);
    }

    private void unRegistTaskReceiver() {
        unregisterReceiver(taskReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == AppConfig.RequestResult.REQUEST_CODE_LOGIN) {
            for (int i = 0; i < mFragments.size(); i++) {
                Fragment fg = mFragments.get(i);
                if (fg instanceof BaseHomeFragment) {
                    if (fg.isAdded()) {
                        ((BaseHomeFragment) fg).refreshFragmentData();
                    }

                }
            }
            return;
        }
        int current = mainViewpager.getCurrentItem();
        switch (current) {
            case 0:
                homeFg.onActivityResult(requestCode, resultCode, data);
                break;
            case 1:
                expertFg.onActivityResult(requestCode, resultCode, data);
                break;
            case 2:
                circleFg.onActivityResult(requestCode, resultCode, data);
                break;
            case 3:
                profileFg.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        ButterKnife.bind(this);
        initialViews();
        registTaskReceiver();
        analysisIntent();

        Beta.autoInit = true;
        Beta.autoCheckUpgrade = true;

        Bugly.init(getApplicationContext(), AppConfig.SDKConfig.BUGLY_APPID, BuildConfig.DEBUG);


        presenter = new MainActivityPresenter(this,this);

        //优先级最高的是用户状态弹窗
        boolean dialogShow = analysisUStatus();
        if(!dialogShow){
            checkOthers();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkDingyuePopStatus();
    }

    //订阅弹窗
    //1.必须登录 2 启动三分钟且超过七天 每月不超过3次
    private void checkDingyuePopStatus(){
        if(InitManager.getInstance().getUser() == null){
            //未登录
            return;
        }
        if(InitManager.getInstance().getCounter() < 180){
            //本次启动不超过三分钟
            return;
        }
        long lastTimePop = PrefUtil.getLong(AppConfig.PrefConfig.PREF_LAST_DINGYUE_POP);
        if((System.currentTimeMillis() - lastTimePop) < 1000*60*60*24*7 ){
            //小于7天
            return;
        }
        String monthlyDingyueCountKey = "monthlyDingyueCountKey_"+ TimeUtil.getCurrentDate();
        int count = PrefUtil.getIntDefaultZero(monthlyDingyueCountKey);
        if(count >= 3){
            //大于3次
            return;
        }
//        DingyueActivity.start(this);
        new DingyueDialog().showDingyueDialog(this);

    }

    private void checkOthers(){
        //added since 3.0.1
        checkNotificationSettings();

        analysisProfiileNoti();

        //弹框广告
        analysisTKDelayed();
    }

    //用户状态弹窗
    private boolean analysisUStatus(){
        if(InitManager.getInstance().getUser() != null
                && !StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().mobile)
            && InitManager.getInstance().getUser().userStatus <= 0){
            new BaseDialog().showUStatusDialog(this, "选择孕育状态", new BaseDialog.OnUStatusSelectedListener() {


                @Override
                public void onUStatusSelected(UStatus status) {
                    Log.d(TAG, "onUStatusSelected: " + status.value + "|");
                    showProgressDialog("请稍候...",false);
                    presenter.updateUStatus(status.id);
                }
            });
            return true;
        }
        return false;
    }

    private void analysisTKDelayed(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //check ads
                if(Cache.tkAd != null){
                    boolean displayed = PrefUtil.getBoolean("TK_"+Cache.tkAd.id);
                    if(!displayed){
                        new BaseDialog().showTKDialog(MainActivity.this,Cache.tkAd);
                    }

                }
            }
        },1000);

    }

    //since 3.0.1检查合伙人通知标志是否显示过
    private void analysisProfiileNoti(){
        boolean flag = PrefUtil.getBoolean(AppConfig.PrefConfig.PREF_PROFILE_NEW);
        if(!flag){
            tabProfile.setNotifyVisiable(true);
        }
    }

    private void checkNotificationSettings(){
        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        // areNotificationsEnabled方法的有效性官方只最低支持到API 19，低于19的仍可调用此方法不过只会返回true，即默认为用户已经开启了通知。
        boolean isOpened = manager.areNotificationsEnabled();
        if(!isOpened){
            new BaseDialog().showConfirmCancelAlert(this, "系统检测到您关闭了消息通知，是否开启?", "去开启", "取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchToNotificationSettings();
                }
            }, null);

        }
    }

    private void switchToNotificationSettings(){
        try {
            // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
            intent.putExtra(Settings.EXTRA_CHANNEL_ID, getApplicationInfo().uid);

            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);

            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
            Intent intent = new Intent();

            //下面这种方案是直接跳转到当前应用的设置界面。
            //https://blog.csdn.net/ysy950803/article/details/71910806
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        }
    }

    public void checkTagSubscribeStatus(){
        boolean subscribed = InitManager.getInstance().getTags() != null && !InitManager.getInstance().getTags().isEmpty();
        if(!subscribed){
            TagSubscribeActivity.start(this,true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegistTaskReceiver();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        analysisIntent();
    }

    private void analysisIntent() {
        Log.d(TAG, "analysisIntent");
        if (getIntent() != null && getIntent().hasExtra("task")) {
            String task = getIntent().getStringExtra("task");
            Log.d(TAG, "task " + task);
            if (task.equals(AppConfig.BroadCastConfig.ACTION_TASK_BBS)
                    || task.equals(AppConfig.BroadCastConfig.ACTION_TASK_REPLY)) {
                setCurrent(2);
            } else if (task.equals(AppConfig.BroadCastConfig.ACTION_TASK_QA)) {
                setCurrent(1);
                expertFg.setDefaultIndex(1);
            } else if (task.equals(AppConfig.BroadCastConfig.ACTION_TASK_LIVE)) {
                setCurrent(1);
                expertFg.setDefaultIndex(0);
            }
        }
    }

    protected void initialViews() {
        tabFunctions.setOnClickListener(this);

        homeFg = HomeFragment.newInstance();
        expertFg = ExpertFragment.newInstance();
        circleFg = CircleFragment.newInstance();
        profileFg = ProfileFragment.newInstance();

        mFragments = new ArrayList<>();
        mFragments.add(homeFg);
        mFragments.add(expertFg);
        mFragments.add(circleFg);
        mFragments.add(profileFg);


        mainViewpager.setOffscreenPageLimit(4);
        mAdapter = new FragmentTabAdapter(getSupportFragmentManager(), mFragments);
        mainViewpager.setAdapter(mAdapter);
        mainViewpager.setOnPageChangeListener(this);

        mainViewpager.setOffscreenPageLimit(4);
        mainTabRadio.setOnCheckedChangeListener(this);


        setCurrent(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mTimestamp == 0) {
                showToast("再次点击退出应用");
                mTimestamp = System.currentTimeMillis();
            } else {
                long timestamp = System.currentTimeMillis();
                if ((timestamp - mTimestamp) < 3 * 1000) {
                    InitManager.getInstance().stopCounter();
                    finish();
                } else {
                    mTimestamp = timestamp;
                    showToast("再次点击退出应用");
                }
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * set current display fragment
     *
     * @param currentIndex
     */
    private void setCurrent(int currentIndex) {
        int radioChildIndex = currentIndex;
        if (currentIndex >= 2) {
            radioChildIndex = currentIndex + 1;
        }
        RadioButton radioButton = (RadioButton) mainTabRadio.getChildAt(radioChildIndex);
        if (!radioButton.isChecked()) {
            radioButton.setChecked(true);
        }

        if (mainViewpager.getCurrentItem() != currentIndex) {
            mainViewpager.setCurrentItem(currentIndex);
        }
        if(currentIndex == 1 || currentIndex == 3){
            circleFg.closeFloatMenu();
            homeFg.closeFloatMenu();
        }
    }

    public void hideProfileNoti(){
        PrefUtil.saveBoolean(AppConfig.PrefConfig.PREF_PROFILE_NEW,true);
        tabProfile.setNotifyVisiable(false);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.tab_home:
                setCurrent(0);
                break;
            case R.id.tab_expert:
                setCurrent(1);
                break;
            case R.id.tab_circle:
                setCurrent(2);
                break;
            case R.id.tab_profile:
                setCurrent(3);
                break;

            default:
                break;
        }
    }

    /**
     * 跳转到专家tab
     * @param index 0显示直播 1显示问答
     */
    public void switchToExpertTab(int index){
        setCurrent(1);
        expertFg.setDefaultIndex(index);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurrent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_functions:
                WebViewActivity.start(this, HttpConfig.WEIDIAN_URL,"花生好孕优选","");
                break;
        }
    }

    public void onFloatMenuClicked(int type){
        switch (type) {
            case FloatMenuMgr.MENU_RECORD:
            case FloatMenuMgr.MENU_BBS:
            case FloatMenuMgr.MENU_ARTICLE:
            case FloatMenuMgr.MENU_ASK:
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(MainActivity.this);
                    return;
                }
                if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().mobile)) {
                    BindMobileActivity.startForResult(MainActivity.this);
                    return;
                }
                if (type == FloatMenuMgr.MENU_ASK) {
                    AskActivity.start(MainActivity.this);
                } else if (type == FloatMenuMgr.MENU_BBS) {
                    TrendPublishActivity.start(MainActivity.this);
                } else if (type == FloatMenuMgr.MENU_ARTICLE) {
                    BBSPublishActivity.start(MainActivity.this);
                } else {
                    CalendarActivity.start(MainActivity.this);
                }
                break;
            case FloatMenuMgr.MENU_SEARCH:
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(MainActivity.this);
                    return;
                }
                SearchActivity.start(MainActivity.this);
                break;
        }
    }

    private BroadcastReceiver taskReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent restart = new Intent(context, MainActivity.class);
            restart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            restart.putExtra("task", intent.getAction());
            startActivity(restart);
            finish();
        }
    };


    @Override
    public void onUpdateUStatusResult(boolean success, String failReason) {
        dismissProgressDialog();
        showToast(success?"更新状态成功":"更新状态失败 "+failReason);
//        checkOthers();
//        DingyueActivity.start(this);
        new DingyueDialog().showDingyueDialog(this);
    }
}
